/**
 * Created by Mac on 2017/6/2.
 */


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import java.io.*;
import java.security.*;
import java.util.Arrays;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

public class Client4 {
    // 搭建客户端
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        MyBC mybc=new MyBC();
        try {
            Socket socket = new Socket("192.168.43.252", 5219);
            System.out.println("客户端启动成功");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter write = new PrintWriter(socket.getOutputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String readline;
            System.out.println("Client:" );
            readline = br.readLine();
            String line=mybc.evaluate(readline);

            // 读取对方的DH公钥
            FileInputStream f1=new FileInputStream(args[0]);
            ObjectInputStream b1=new ObjectInputStream(f1);
            PublicKey  pbk=(PublicKey)b1.readObject( );
//读取自己的DH私钥
            FileInputStream f2=new FileInputStream(args[1]);
            ObjectInputStream b2=new ObjectInputStream(f2);
            PrivateKey  prk=(PrivateKey)b2.readObject( );
            // 执行密钥协定
            KeyAgreement ka=KeyAgreement.getInstance("DH");
            ka.init(prk);
            ka.doPhase(pbk,true);
            //生成共享信息
            byte[ ] sb=ka.generateSecret();
            System.out.println(sb.length);
            byte[]ssb=new byte[24];
            for(int i=0;i<24;i++)
                ssb[i]=sb[i];
            Key k=new SecretKeySpec(ssb,"DESede");



            Cipher cp=Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext[]=line.getBytes("UTF-8");


            byte ctext[]=cp.doFinal(ptext);
            String Str=new String(ctext,"ISO-8859-1");

            write.println(Str);
            write.flush();






            System.out.println("Server return:" + in.readLine());

            write.close();
            in.close();
            socket.close();

        } catch (Exception e) {
            System.out.println("can not listen to:" + e);
        }

    }

}
